<?php

$upDir = "media";

$id     = $_POST['PersonID'];

echo "<pre>";
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
	//print_r($_FILES);
	switch ($_FILES['userfile']['type']) {
	case "image/jpeg":
	case "image/pjpeg":
	case "image/gif":
		$mediatype = "img";
		break;
	case "audio/x-ms-wma":
	case "audio/aiff":
	case "audio/wav":
	case "audio/mpeg":
		$mediatype = "audio";
		break;
	default:
		echo "Did not recognize file type ({$_FILES['userfile']['type']}).\n";
		exit;
		break;
	}

	$mTitle = $_POST['Title'];
	$mDescr = $_POST['Descr'];


	// CONNECT TO DB

	$link = mysql_connect("localhost", "ftreemod", "ftree_mod")
	   or dieErr("Could not connect : " . mysql_error());
	mysql_select_db("ftree") or dieErr("Could not select database");


//INSERT INTO `media` ( `id` , `type` , `link_table` , `link_id` , `title` , `descr` , `path` )
//VALUES (
//'', 'test', 'person', '1', 'Title', 'descr', '/this/is/path.jpg'
//);

	$query  = "INSERT INTO `media` ( `type` ) VALUES ( '$mediatype' )";	//first add to get an id #
										//then use id # for file name
        $result = mysql_query($query) or die("INSERT failed. File not stored: " . mysql_error());
	$mediaID = mysql_insert_id();
	$newFName = ${id} . "-" . $mediaID;
	$matched  = preg_match("/\.[A-Za-z0-9]{1,4}$/", $_FILES['userfile']['name'], $newFExt);  //get orig file extension
	if ($matched) { $newFName .= "{$newFExt[0]}"; }
	$newFPath = $upDir . "/" . $mediatype . "/" . $newFName;

	if (! move_uploaded_file($_FILES['userfile']['tmp_name'], $newFPath)) {
		echo "Could not save file under new name ($newFName).\n";
		exit;
	}

//UPDATE `media` SET `link_table` = 'person',
//`link_id` = '1',
//`title` = 'Title',
//`descr` = 'description',
//`path` = '/file/path' WHERE `id` = '10' LIMIT 1 ;

	$query  = "UPDATE `media` SET	`link_table` = 'person',
					`link_id` = '$id',
					`title` = '$mTitle',
					`descr` = '$mDescr',
					`path` = '$newFName'
		WHERE `id` = '$mediaID' LIMIT 1";

	// PERFORM UPDATE

	$result = mysql_query($query) or die("Query failed : " . mysql_error());

	mysql_close($link);

	echo "Successfully uploaded file.\n";
	echo "Info: size = {$_FILES['userfile']['size']}\n      type = {$_FILES['userfile']['type']}\n";

} else {
	echo "Could not upload file to \"$fpath\": ";
	switch ($_FILES['userfile']['error']) {
	case UPLOAD_ERR_INI_SIZE:
		echo "File size exceeds PHP limit.\n"; break;
	case UPLOAD_ERR_FORM_SIZE:
		echo "File size exceeds form limit.\n"; break;
	case UPLOAD_ERR_PARTIAL:
		echo "File only partially uploaded.\n"; break;
	case UPLOAD_ERR_NO_FILE:
		echo "No file was received.\n"; break;
	default:
		echo "Unknown upload error.\n"; break;
	}
	//print_r($_FILES);
}
echo "\n<a href=\"person_media.php?id=$id#Add\">Click here</a> to go back to the Media page.\n";
echo "</pre>";

?>
